package com.summer.commonException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "异常处理API")
@Slf4j
@RestControllerAdvice // 相当于ControllerAdvice + ResponseBody
public class XueChengExceptionHandler {

    // TODO : 一个方法相当于一个catch子句 @ResponseStatus返回响应状态码
    // 自定义异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 响应状态码500
    @ExceptionHandler(XueChengException.class)
    public RestErrorResponse catchXueChengException(XueChengException e){
        log.info("捕获到自定义异常{}", e.getErrorMsg(), e);
        e.printStackTrace();
        return new RestErrorResponse(e.getErrorMsg());
    }

    // 系统未知异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 响应状态码500
    @ExceptionHandler(Exception.class)
    public RestErrorResponse catchSystemException(Exception e){
        if ("不允许访问".equals(e.getMessage())){
            e.printStackTrace();
            return new RestErrorResponse("您无权访问");
        }
        log.info("捕获到系统异常{}", e.getMessage(), e);
        e.printStackTrace();
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
    }

    // 参数校验异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 响应状态码500
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RestErrorResponse catchMethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<String> msgList = new ArrayList<>();

        bindingResult.getFieldErrors().stream().forEach(item->msgList.add(item.getDefaultMessage()));
        //拼接错误信息
        String msg = StringUtils.join(msgList, ",");
        log.info("捕获到参数校验异常{}", msg);
        e.printStackTrace();
        return new RestErrorResponse(msg);
    }
}
